<!--suppress ALL -->
<template>
  <div class="scroll-y columnSS" style="gap: 10px;">
    <div class="rowCC widthPC-100" :style="{ height: `calc(100vh - ${settings.delWindowHeight})`}">
      <el-form
        ref="refForm"
        label-width="100px"
        :model="subForm"
        :rules="formRules"
        class="pr-5 bg-light-secondary p-1">
        <el-form-item label="账号" prop="account" :rules="formRules.isNotNull('账号不能为空')" label-position="left">
          <el-input v-model="subForm.account" maxlength="20" placeholder="账号" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname" :rules="formRules.isNotNull('昵称不能为空')" label-position="left">
          <el-input v-model="subForm.nickname" maxlength="20" placeholder="昵称" />
        </el-form-item>
        <el-form-item label="角色" prop="role" :rules="formRules.isNotNull('请选择角色')" label-position="left">
          <el-select v-model="subForm.role" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.slug"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <div class="block rowCC" style="width: 100%">
      <el-button type="primary" @click="onClickSubForm">确定</el-button>
      <el-button type="warning" @click="onClickGoBack">取消</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import {onMounted, reactive, ref} from 'vue'
import {useRoute} from 'vue-router'
import settings from "@/settings";
import router from "@/router";
import {elMessage, useElement} from '@/hooks/use-element'
import { addUserReq, editUserReq, getRoleReq } from "@/api/setting";

const formRules = useElement().formRules
const route = useRoute();

onMounted(() => {
  getRoleListData();
});

const refForm = ref();
let subForm = reactive({
  account: route.params?.account,
  nickname: route.params?.nickname,
  role: route.params?.role
});
let options = ref([]);
const formId = ref(route.params?.id || 0);

const getRoleListData = () => {
  getRoleReq({
    page: 1,
    pageSize: 500
  }).then(res => {
    options.value = res.data.list;
  });
};

const onClickSubForm = () => {
  let data = JSON.parse(JSON.stringify(subForm));
  console.log(formId.value, data);
  refForm.value.validate((valid) => {
    return
    if (valid) {
      data.roles = [data.role];
      if (formId.value) {
        editUserReq(formId.value, data).then(_ => {
          elMessage("编辑成功");
          onClickGoBack();
        });
      } else {
        addUserReq(data).then(_ => {
          elMessage("添加成功");
          onClickGoBack();
        });
      }
    }
  });
};

const onClickGoBack = () => {
  router.back();
};
</script>

<style lang="scss" scoped>

</style>
